﻿using NLog;
using System.Diagnostics;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace StructuredProgrammingAssignment.Models.Helpers
{
	public class PerformanceFilter : ActionFilterAttribute
	{
		private Stopwatch stopWatch = new Stopwatch();
		private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

		public override void OnActionExecuting(HttpActionContext actionContext) {
			base.OnActionExecuting(actionContext);

			stopWatch.Reset();
			stopWatch.Start();
		}

		public override void OnActionExecuted(HttpActionExecutedContext actionContext) {
			base.OnActionExecuted(actionContext);

			stopWatch.Stop();
			var executionTime = stopWatch.ElapsedMilliseconds;

			string controller = actionContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();
			string action = actionContext.ActionContext.ActionDescriptor.ActionName.ToLower();
			string path = actionContext.ActionContext.Request.RequestUri.PathAndQuery.ToString();

			SPLog.Trace("performance", executionTime.ToString(), controller, action, path);
		}
	}
}